package com.apes.framework.condition;

import com.apestech.framework.db.SqlSession;
import com.apestech.framework.json.JSON;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.callback.MasterSaveInter;
import com.apestech.framework.util.LocalVariable;
import com.apestech.framework.xml.plugin.modul.SysCondition;

import java.util.ArrayList;
import java.util.Map;

/**
 * @author hup
 * @create 2020-01-02-11:09
 */
public class ConSaveInter implements MasterSaveInter {
    private SqlSession session;
    private SysCondition sysCondition;

    public ConSaveInter(SqlSession session) throws Exception {
        this.session=session;
        sysCondition= LocalVariable.getConfig().getSysCondition(session);
    }

    @Override
    public JSONObject getJSON(JSONObject input) throws Exception {
        ArrayList<String> klist=input.getKeylist();
        for(String k: klist){
            Object value=input.get(k);
            if(value instanceof Map){
                value= JSON.toJSON(value);
                if(((JSONObject) value).get("id")!=null) {
                    input.put(k, ((JSONObject) value).get("id"));
                } else if(((JSONObject) value).get("ID")!=null && ((JSONObject) value).get("NAME")!=null){
                    input.put(k, ((JSONObject) value).get("ID"));
                } else {
                    String key=session.getTheme()+"."+k;
                    JSONObject m= sysCondition.getDimensionField(key);
                    if(m!=null){
                        input.put(k, ((JSONObject) value).get(m.getString("field")));
                    }
                }
            }
        }
        return input;
    }
}
